package com.example.xunai.controller;

import com.example.xunai.entity.TokenUsage;
import com.example.xunai.entity.User;
import com.example.xunai.service.user.TokenUsageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/stats")
@RequiredArgsConstructor
public class StatsController {

    private final TokenUsageService tokenUsageService;

    /**
     * 获取用户token使用统计（按模型分组）
     */
    @GetMapping("/tokens/by-model")
    public ResponseEntity<?> getUserTokenStatsByModel(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }

        // 设置默认日期范围（最近30天）
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(30);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }

        try {
            List<Map<String, Object>> stats = tokenUsageService.getUserTokenStats(user.getId(), startDate, endDate);
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取token统计失败", e);
            return ResponseEntity.status(500).body("获取统计失败");
        }
    }

    /**
     * 获取用户token使用汇总统计
     */
    @GetMapping("/tokens/summary")
    public ResponseEntity<?> getUserTokenSummary(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }

        // 设置默认日期范围（最近30天）
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(30);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }

        try {
            Map<String, Object> summary = tokenUsageService.getUserTokenSummary(user.getId(), startDate, endDate);
            return ResponseEntity.ok(summary);
        } catch (Exception e) {
            log.error("获取token汇总统计失败", e);
            return ResponseEntity.status(500).body("获取汇总统计失败");
        }
    }

    /**
     * 获取用户每日token趋势
     */
    @GetMapping("/tokens/daily")
    public ResponseEntity<?> getUserDailyTokenTrend(
            @RequestParam(defaultValue = "30") int days,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }

        try {
            List<Map<String, Object>> trend = tokenUsageService.getUserDailyTokenTrend(user.getId(), days);
            return ResponseEntity.ok(trend);
        } catch (Exception e) {
            log.error("获取每日token趋势失败", e);
            return ResponseEntity.status(500).body("获取趋势失败");
        }
    }

    /**
     * 获取模型使用统计（管理员功能）
     */
    @GetMapping("/models")
    public ResponseEntity<?> getModelUsageStats(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        // 设置默认日期范围
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(30);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }

        try {
            List<Map<String, Object>> stats = tokenUsageService.getModelUsageStats(startDate, endDate);
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取模型使用统计失败", e);
            return ResponseEntity.status(500).body("获取统计失败");
        }
    }

    /**
     * 获取用户最近使用的模型
     */
    @GetMapping("/models/recent")
    public ResponseEntity<?> getUserRecentModels(
            @RequestParam(defaultValue = "5") int limit,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }

        try {
            List<String> recentModels = tokenUsageService.getUserRecentModels(user.getId(), limit);
            return ResponseEntity.ok(recentModels);
        } catch (Exception e) {
            log.error("获取最近使用模型失败", e);
            return ResponseEntity.status(500).body("获取模型列表失败");
        }
    }

    /**
     * 获取对话的token使用详情
     */
    @GetMapping("/conversation/{conversationId}/tokens")
    public ResponseEntity<?> getConversationTokenUsage(
            @PathVariable Long conversationId,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }

        try {
            List<TokenUsage> usage = tokenUsageService.getConversationTokenUsage(conversationId);
            return ResponseEntity.ok(usage);
        } catch (Exception e) {
            log.error("获取对话token使用详情失败", e);
            return ResponseEntity.status(500).body("获取详情失败");
        }
    }

    /**
     * 获取用户token使用总量
     */
    @GetMapping("/tokens/total")
    public ResponseEntity<?> getUserTotalTokenUsage(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }

        // 设置默认日期范围（最近30天）
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(30);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }

        try {
            Map<String, Integer> totalUsage = tokenUsageService.getUserTotalTokenUsage(user.getId(), startDate, endDate);
            return ResponseEntity.ok(totalUsage);
        } catch (Exception e) {
            log.error("获取token总量失败", e);
            return ResponseEntity.status(500).body("获取总量失败");
        }
    }

    /**
     * 检查用户是否超过token限制
     */
    @GetMapping("/tokens/limit-check")
    public ResponseEntity<?> checkTokenLimit(
            @RequestParam int limit,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }

        // 设置默认日期范围（本月）
        if (startDate == null) {
            startDate = LocalDate.now().withDayOfMonth(1);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }

        try {
            boolean isExceeded = tokenUsageService.isUserExceededTokenLimit(user.getId(), startDate, endDate, limit);
            Map<String, Object> result = Map.of(
                    "exceeded", isExceeded,
                    "userId", user.getId(),
                    "limit", limit,
                    "period", Map.of("startDate", startDate, "endDate", endDate)
            );
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("检查token限制失败", e);
            return ResponseEntity.status(500).body("检查限制失败");
        }
    }

    /**
     * 获取用户所有token使用记录
     */
    @GetMapping("/tokens/records")
    public ResponseEntity<?> getUserTokenUsageRecords(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.status(401).build();
        }

        // 设置默认日期范围（最近30天）
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(30);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }

        try {
            List<TokenUsage> records = tokenUsageService.getUserTokenUsageRecords(user.getId(), startDate, endDate);
            return ResponseEntity.ok(records);
        } catch (Exception e) {
            log.error("获取token使用记录失败", e);
            return ResponseEntity.status(500).body("获取记录失败");
        }
    }

    /**
     * 获取系统总体token统计（管理员功能）
     */
    @GetMapping("/system/summary")
    public ResponseEntity<?> getSystemTokenSummary(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        // 设置默认日期范围
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(30);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }

        try {
            Map<String, Object> summary = tokenUsageService.getSystemTokenSummary(startDate, endDate);
            return ResponseEntity.ok(summary);
        } catch (Exception e) {
            log.error("获取系统token统计失败", e);
            return ResponseEntity.status(500).body("获取系统统计失败");
        }
    }
}